package com.kim.bookshop.category.daoimpl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.itcast.jdbc.TxQueryRunner;

import com.kim.bookshop.category.bean.Category;
import com.kim.bookshop.category.dao.CategoryDao;

public class CategoryDaoImpl implements CategoryDao {

	private QueryRunner qr=new TxQueryRunner();
	
	@Override
	public List<Category> findAll() {
		String sql="select * from category";
		try {
			return qr.query(sql, new BeanListHandler<Category>(Category.class));
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		
	}

	@Override
	public void add(Category category) {
		String sql="insert into category (cid,cname) values(?,?)";
		try {
			qr.update(sql,category.getCid(),category.getCname());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}

	@Override
	public void delete(String cid) {
		String sql="delete from category where cid=?";
		try {
			qr.update(sql,cid);
		} catch (SQLException e) {
			throw new RuntimeException("该分类下有关联书籍，不能删除");
		}

	}

	@Override
	public void edit(Category category) {
		String sql="update category set cname=? where cid=?";
		try {
			qr.update(sql,category.getCname(),category.getCid());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}


	@Override
	public Category load(String cid) {
		try {
			String sql="select * from category where cid=?";
			return qr.query(sql, new BeanHandler<Category>(Category.class),cid);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

}
